package com.jerry.jmx.utils;

import java.util.HashMap;
import java.util.Map;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jerry.utils.str.Jutils;

public class JMXConn {

	private static final Logger log = LoggerFactory.getLogger(JMXConn.class);

	public static JMXConnector getConn(String host, int portnum) {
		String hostName = host;
		int portNum = portnum;
		JMXConnector c = null;
		log.debug("test into jmxconn.getconn method!" + portnum);
		try {
			JMXServiceURL u = new JMXServiceURL(
					"service:jmx:rmi:///jndi/rmi://" + hostName + ":" + portNum + "/jmxrmi");

			Map<String, Object> auth = new HashMap<String, Object>();
			auth.put(JMXConnector.CREDENTIALS,
					new String[] { Jutils.getProperty("jmx.user").trim(), Jutils.getProperty("jmx.password").trim() });
			log.debug("test jmx user : " + Jutils.getProperty("jmx.user"));
			log.debug("test jmx passwd : " + Jutils.getProperty("jmx.password"));
			log.debug("the u is:" + u);
			c = JMXConnectorFactory.connect(u, auth);
			log.debug("test jmx conn1111: " + c);

		} catch (Exception e) {
			// e.printStackTrace();
		}
		return c;
	}

	public static boolean checkJMX(String host, int portnum) {
		boolean ret = false;
		log.debug("测试jmx 1 " + ret);
		JMXConnector jc = JMXConn.getConn(host, portnum);
		log.debug("测试jmx 2 " + jc);
		if (jc != null) {
			ret = true;
		}
		return ret;
	}

	public static void main(String[] args) {
//		JMXConnector conn=JMXConn.getConn("172.16.12.128", 9999);
//		System.out.println("the conn: "+conn);
	}

}
